import { createApp, h, type App } from 'vue'
import LoadingDialog from './LoadingDialog.vue'
import emitter from '@/main'
import { log } from '@/utils/com'
import { EmitterChannel } from '@/utils/constant'

let loadingInstance: App<Element> | null = null
let container: HTMLDivElement | null = null
let currentPromise: Promise<boolean> | null = null

export function showLoading(msg?: string, fix?: boolean): Promise<boolean> {
  return new Promise((resolve) => {
    // 如果已有实例，先销毁
    if (loadingInstance) {
      //emitterChannelLoading
      emitter.emit(EmitterChannel.Loading, msg)
      return currentPromise as Promise<boolean>
      // hideLoading()
    }
    container = document.createElement('div')
    document.body.appendChild(container)
    currentPromise = new Promise((res) => {
      log(res)
      // resolveCallback = res
    })

    loadingInstance = createApp({
      render() {
        return h(LoadingDialog, {
          msg,
          fix,
          onClickCallback: (type: number) => {
            resolve(type === 1)
            hideLoading()
          },
        })
      },
    })
    loadingInstance.mount(container)
  })
}

export function hideLoading() {
  if (!loadingInstance) return
  // 销毁实例
  loadingInstance.unmount()
  if (container && container.parentNode) {
    container.parentNode.removeChild(container)
  }
  loadingInstance = null
  container = null
}
